package com.service.impl;

import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.common.BaseResponse;
import com.common.ResultUtils;
import com.constant.UserConstant;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.common.ErrorCode;
import com.domain.dto.UserInfo;
import com.domain.entity.ApplyFriend;
import com.domain.entity.User;
import com.domain.entity.UserFriend;
import com.domain.request.ApplyFriendRequest;
import com.exception.BusinessException;
import com.exception.NoDateException;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.mapper.UsersMapper;
import com.service.ApplyFriendService;
import com.service.UserFriendService;
import com.service.UsersService;
import com.util.AlgorithmUtils;
import com.ws.event.FriendEvent;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.math3.util.Pair;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationEventPublisher;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.util.DigestUtils;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.*;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Collectors;

import static com.constant.UserConstant.*;

/**
 * @author Administrator
 * @description 针对表【users】的数据库操作Service实现
 * @createDate 2024-05-17 10:58:25
 */
@Service
@Slf4j
public class UsersServiceImpl extends ServiceImpl<UsersMapper, User>
        implements UsersService {
    @Autowired
    private UsersMapper userMapper;
    @Resource
    private ThreadPoolExecutor completableFuturePool;

    @Autowired
    private ApplyFriendService applyFriendService;
    @Autowired
    private UserFriendService userFriendService;
    @Autowired
    private ApplicationEventPublisher applicationEventPublisher;

    /**
     * 用户注册
     *
     * @param userAccount
     * @param userPassword
     * @param checkPassword
     * @return
     */
    @Override
    public long userRegister(String userAccount, String userPassword, String checkPassword) {
        // 1. 校验
        if (StringUtils.isAnyBlank(userAccount, userPassword, checkPassword)) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "参数为空");
        }
        if (userAccount.length() < 4) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "用户账号过短");
        }
        if (userPassword.length() < 8 || checkPassword.length() < 8) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "用户密码过短");
        }
        // 账户不能包含特殊字符
        String validPattern = "[`~!@#$%^&*()+=|{}':;',\\\\[\\\\].<>/?~！@#￥%……&*（）——+|{}【】‘；：”“’。，、？]";
        Matcher matcher = Pattern.compile(validPattern).matcher(userAccount);
        if (matcher.find()) {
            return -1;
        }
        // 密码和校验密码相同
        if (!userPassword.equals(checkPassword)) {
            return -1;
        }
        // 账户不能重复
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_account", userAccount);
        long count = userMapper.selectCount(queryWrapper);
        if (count > 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "账号重复");
        }
        // 2. 加密
        String encryptPassword = DigestUtils.md5DigestAsHex(userPassword.getBytes());
        // 3. 插入数据
        User user = new User();
        user.setUserAccount(userAccount);
        user.setUserPassword(encryptPassword);
        user.setLastLoginTime(new Date(System.currentTimeMillis()));
        boolean saveResult = this.save(user);
        if (!saveResult) {
            return -1;
        }
        return user.getId();
    }

    /**
     * 获取最匹配的用户
     *
     * @param num
     * @param loginUser
     * @return
     */
    int[][] record;

    @Override
    public List<User> matchUsers(long num, User loginUser) {
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.select("id", "tags");
        queryWrapper.isNotNull("tags");
        List<User> userList = this.list(queryWrapper);
        String tags = loginUser.getTags();
        Gson gson = new Gson();
        List<String> tagList = gson.fromJson(tags, new TypeToken<List<String>>() {
        }.getType());
        // 用户列表的下标 => 相似度
        List<Pair<User, Long>> list = new ArrayList<>();
        // 依次计算所有用户和当前用户的相似度
        for (int i = 0; i < userList.size(); i++) {
            User user = userList.get(i);
            String userTags = user.getTags();
            // 无标签或者为当前用户自己
            if (StringUtils.isBlank(userTags) || Objects.equals(user.getId(), loginUser.getId())) {
                continue;
            }
            List<String> userTagList = gson.fromJson(userTags, new TypeToken<List<String>>() {
            }.getType());
            // 计算分数
            long distance = AlgorithmUtils.minDistance(tagList, userTagList);
            list.add(new Pair<>(user, distance));
        }
        // 按编辑距离由小到大排序
        List<Pair<User, Long>> topUserPairList = list.stream()
                .sorted((a, b) -> (int) (a.getValue() - b.getValue()))
                .limit(num)
                .collect(Collectors.toList());
        // 原本顺序的 userId 列表
        List<Long> userIdList = topUserPairList.stream().map(pair -> pair.getKey().getId()).collect(Collectors.toList());
        QueryWrapper<User> userQueryWrapper = new QueryWrapper<>();
        userQueryWrapper.in("id", userIdList);
        // 1, 3, 2
        // User1、User2、User3
        // 1 => User1, 2 => User2, 3 => User3
        Map<Long, List<User>> userIdUserListMap = this.list(userQueryWrapper)
                .stream()
                .map(user -> getSafetyUser(user))
                .collect(Collectors.groupingBy(User::getId));
        List<User> finalUserList = new ArrayList<>();
        for (Long userId : userIdList) {
            finalUserList.add(userIdUserListMap.get(userId).get(0));
        }
        return finalUserList;
    }

    /**
     * 好友申请
     *
     * @param applyFriendRequest
     * @param currentUserId
     * @return
     */
    @Override
    public BaseResponse<Boolean> applyFriend(ApplyFriendRequest applyFriendRequest, Long currentUserId) {
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("id", applyFriendRequest.getUserId());
        User user = getOne(queryWrapper);
        if (user == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "用户不存在");
        }
        QueryWrapper<UserFriend> wrapper = new QueryWrapper<>();
        wrapper.eq("user_id", currentUserId);
        List<UserFriend> userFriends = userFriendService.list(wrapper);
        boolean isFriend = false;
        if (userFriends != null) {
            for (UserFriend userFriend : userFriends) {
                if (Objects.equals(userFriend.getFriendId(), applyFriendRequest.getUserId())) {
                    isFriend = true;
                    break;
                }
            }
            if (isFriend) {
                throw new BusinessException(ErrorCode.PARAMS_ERROR, "已经是好友");
            }
        }
        ApplyFriend applyFriend = applyFriendRequestToApplyFriend(applyFriendRequest, currentUserId);
        //将数据存到数据库中
        boolean save = applyFriendService.save(applyFriend);
        if (!save) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "申请失败");
        }
        FriendEvent friendEvent = new FriendEvent(applyFriend);
        applicationEventPublisher.publishEvent(friendEvent);
        return ResultUtils.success(true);
    }

    /**
     * 获取好友申请列表
     *
     * @param id
     * @return
     */
    @Override
    public List<ApplyFriend> getApplyFriendList(Long id) {
        QueryWrapper<ApplyFriend> applyFriendQueryWrapper = new QueryWrapper<>();
        applyFriendQueryWrapper.eq("user_id", id);
        List<ApplyFriend> friendList = applyFriendService.list(applyFriendQueryWrapper);
        if (CollectionUtils.isEmpty(friendList)) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "无申请记录");
        }
        return friendList;
    }

    private static ApplyFriend applyFriendRequestToApplyFriend(ApplyFriendRequest applyFriendRequest, Long currentUserId) {
        ApplyFriend applyFriend = new ApplyFriend();
        applyFriend.setApplyUserId(currentUserId);
        applyFriend.setUserId(applyFriendRequest.getUserId());
        applyFriend.setText(applyFriendRequest.getText());
        applyFriend.setStatus(0);
        applyFriend.setCreateTime(new Date(System.currentTimeMillis()));
        return applyFriend;
    }

    public int dp(String targetTag, int i, String tags, int j) {
        if (i == -1) {
            return j + 1;
        }
        if (j == -1) {
            return i + 1;
        }
        if (record[i][j] != -1) {
            return record[i][j];
        }

        if (targetTag.charAt(i) == tags.charAt(j)) {
            record[i][j] = dp(targetTag, i - 1, tags, j - 1) + 1;
        } else {
            record[i][j] = min(dp(targetTag, i - 1, tags, j),
                    dp(targetTag, i, tags, j - 1),
                    dp(targetTag, i - 1, tags, j - 1)) + 1;
        }
        return record[i][j];
    }

    int min(int a, int b, int c) {
        return Math.min(a, Math.min(b, c));
    }

    /**
     * 获取当前登录用户信息
     *
     * @param request
     * @return
     */
    @Override
    public User getLoginUser(HttpServletRequest request) {
        if (request == null) {
            return null;
        }
        Object userObj = request.getSession().getAttribute(USER_LOGIN_STATE);
        if (userObj == null) {
            throw new BusinessException(ErrorCode.NO_AUTH);
        }
        return (User) userObj;
    }

    /**
     * 用户登录
     *
     * @param userAccount
     * @param userPassword
     * @param request
     * @return
     */
    @Override
    public User userLogin(String userAccount, String userPassword, HttpServletRequest request) {
        // 1. 校验
        if (StringUtils.isAnyBlank(userAccount, userPassword)) {
            return null;
        }
        if (userAccount.length() < 4) {
            return null;
        }
        if (userPassword.length() < 8) {
            return null;
        }
        // 账户不能包含特殊字符
        String validPattern = "[`~!@#$%^&*()+=|{}':;',\\\\[\\\\].<>/?~！@#￥%……&*（）——+|{}【】‘；：”“’。，、？]";
        Matcher matcher = Pattern.compile(validPattern).matcher(userAccount);
        if (matcher.find()) {
            return null;
        }
        // 2. 加密
        String encryptPassword = DigestUtils.md5DigestAsHex(userPassword.getBytes());
        // 查询用户是否存在
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_account", userAccount);
        queryWrapper.eq("user_password", encryptPassword);
        User user = userMapper.selectOne(queryWrapper);
        // 用户不存在
        if (user == null) {
            log.info("user login failed, userAccount cannot match userPassword");
            return null;
        }
        setLoginTime(user);
        // 3. 用户脱敏
        User safetyUser = getSafetyUser(user);
        // 4. 记录用户的登录态
        request.getSession().setAttribute(USER_LOGIN_STATE, safetyUser);
        return safetyUser;
    }

    private void setLoginTime(User user) {
        UpdateWrapper<User> updateWrapper = new UpdateWrapper<>();
        updateWrapper.set("login_time", user.getLoginTime()).set("user_status", LOGIN).eq("id", user.getId());
        update(updateWrapper);
    }

    /**
     * 用户脱敏
     *
     * @param originUser
     * @return
     */
    @Override
    public User getSafetyUser(User originUser) {
        if (originUser == null) {
            return null;
        }
        User safetyUser = new User();
        safetyUser.setId(originUser.getId());
        safetyUser.setUsername(originUser.getUsername());
        safetyUser.setUserAccount(originUser.getUserAccount());
        safetyUser.setAvatarUrl(originUser.getAvatarUrl());
        safetyUser.setGender(originUser.getGender());
        safetyUser.setPhone(originUser.getPhone());
        safetyUser.setEmail(originUser.getEmail());
        safetyUser.setUserRole(originUser.getUserRole());
        safetyUser.setUserStatus(originUser.getUserStatus());
        safetyUser.setCreateTime(originUser.getCreateTime());
        safetyUser.setTags(originUser.getTags());
        return safetyUser;
    }

    /**
     * 更改用户信息
     *
     * @param user
     * @param loginUser
     * @return
     */
    @Override
    public int updateUser(User user, User loginUser) {
        long userId = user.getId();
        if (userId <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        //  如果用户没有传任何要更新的值，就直接报错，不用执行 update 语句
        if (isEmptyUser(user)) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        // 如果是管理员，允许更新任意用户
        // 如果不是管理员，只允许更新当前（自己的）信息
        if (!isAdmin(loginUser) && userId != loginUser.getId()) {
            throw new BusinessException(ErrorCode.NO_AUTH);
        }
        User oldUser = userMapper.selectById(userId);
        if (oldUser == null) {
            throw new BusinessException(ErrorCode.NULL_ERROR);
        }
        return userMapper.updateById(user);
    }

    /**
     * 是否为管理员
     *
     * @param loginUser
     * @return
     */
    @Override
    public boolean isAdmin(User loginUser) {
        return loginUser != null && loginUser.getUserRole() == UserConstant.ADMIN_ROLE;
    }

    /**
     * 是否为管理员
     *
     * @param request
     * @return
     */
    @Override
    public boolean isAdmin(HttpServletRequest request) {
        // 仅管理员可查询
        Object userObj = request.getSession().getAttribute(USER_LOGIN_STATE);
        User user = (User) userObj;
        return user != null && user.getUserRole() == UserConstant.ADMIN_ROLE;
    }

    /**
     * 判断用户是否为空
     *
     * @param user
     * @return
     */
    private boolean isEmptyUser(User user) {
        return user.getUserRole() != null && user.getUserPassword() != null && user.getUserAccount() != null &&
                user.getUserStatus() != null && user.getEmail() != null
                && user.getAvatarUrl() != null && user.getPhone() != null && user.getGender() != null;
    }

    /**
     * 登出用户
     *
     * @param request
     */
    @Override
    public int userLogout(HttpServletRequest request) {
        // 移除登录态
        User loginUser = getLoginUser(request);
        loginUser.setLastLoginTime(new Date(System.currentTimeMillis()));
        loginUser.setUserStatus(LOGOUT);
        request.getSession().removeAttribute(USER_LOGIN_STATE);
        UpdateWrapper<User> wrapper = new UpdateWrapper<>();
        wrapper.set("user_status", LOGOUT).set("last_login_time", new Date(System.currentTimeMillis())).eq("id", loginUser.getId());
        update(wrapper);
        return 1;
    }

    /**
     * 根据多个标签获取用户
     *
     * @param tags
     * @return
     */
    @Override
    public BaseResponse<ArrayList<UserInfo>> getUserByTag(ArrayList<String> tags) throws ExecutionException, InterruptedException {
        ArrayList<User> users = (ArrayList<User>) list();
        CompletableFuture<ArrayList<User>> memoryComputerFuture = CompletableFuture.supplyAsync(() -> memoryComputing(tags, users),
                completableFuturePool);
        CompletableFuture<ArrayList<User>> datebaseCalculateFuture = CompletableFuture.supplyAsync(() -> byDatebaseCalculate(tags),
                completableFuturePool);
        //使用异步去执行
        CompletableFuture<ArrayList<UserInfo>> anyOf = CompletableFuture
                .anyOf(memoryComputerFuture, datebaseCalculateFuture)
                .thenApply((result) -> handlerUsers((ArrayList<User>) result));
        ArrayList<UserInfo> data = anyOf.get();
        return ResultUtils.success(data);
    }

    private ArrayList<UserInfo> handlerUsers(ArrayList<User> datas) {
        ArrayList<UserInfo> arrayList = new ArrayList<>();
        datas.forEach(data -> {
            UserInfo userInfo = desensitization(data);
            arrayList.add(userInfo);
        });
        return arrayList;
    }

    /**
     * 对用户信息进行脱敏
     *
     * @param data
     */
    private static UserInfo desensitization(User data) {
        UserInfo user = new UserInfo();
        user.setId(data.getId());
        user.setSex(data.getGender());
        user.setEmail(data.getEmail());
        user.setPhone(data.getPhone());
        user.setTag(data.getTags());
        user.setAvatarUrl(data.getAvatarUrl());
        user.setUsername(data.getUsername());
        user.setCreateTime(data.getCreateTime());
        user.setUpdateTime(data.getUpdateTime());
        return user;
    }

    /**
     * 从数据库中获取所有用户在内存中进行计算
     *
     * @param tags
     */
    private ArrayList<User> memoryComputing(ArrayList<String> tags, ArrayList<User> users) {
        return (ArrayList<User>) users.stream().filter(user -> isFilter(tags, user)).collect(Collectors.toList());
    }

    /**
     * 过滤掉不符合标签的用户
     *
     * @param tags
     * @param user
     * @return
     */
    private static boolean isFilter(ArrayList<String> tags, User user) {
        boolean flag = true;
        for (String tag : tags) {
            if (!user.getTags().contains(tag)) {
                flag = false;
                break;
            }
        }
        return flag;
    }

    /**
     * 通过数据库模糊匹配获取用户
     *
     * @param tags
     * @return
     */
    private ArrayList<User> byDatebaseCalculate(ArrayList<String> tags) {
        ArrayList<User> data;
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        for (String tag : tags) {
            queryWrapper = queryWrapper.like("tag", tag);
        }
        List<User> users = userMapper.selectList(queryWrapper);
        if (CollectionUtils.isEmpty(users)) {
            throw new NoDateException("没有数据了!");
        }
        data = (ArrayList<User>) users;
        return data;
    }
}




